package com.zrrd.blog.system.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.zrrd.blog.api.entities.SysUser;
import com.zrrd.blog.api.entities.UserInfoREQ;
import com.zrrd.blog.api.feign.IFeignArticleController;
import com.zrrd.blog.api.feign.IFeignQuestionController;
import com.zrrd.blog.system.mapper.SysUserMapper;
import com.zrrd.blog.system.req.RegisterREQ;
import com.zrrd.blog.system.req.SysUserCheckPasswordREQ;
import com.zrrd.blog.system.req.SysUserREQ;
import com.zrrd.blog.system.req.SysUserUpdatePasswordREQ;
import com.zrrd.blog.system.service.ISysUserService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zrrd.blog.util.base.Result;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

/**
 * <p>
 * 用户信息表 服务实现类
 * </p>
 *
 * @author chen
 * @since 2023-08-11
 */
@Service
public class SysUserServiceImpl extends ServiceImpl<SysUserMapper, SysUser> implements ISysUserService {

    @Override
    public Result queryPage(SysUserREQ req) {
        QueryWrapper<SysUser> wrapper=new QueryWrapper<>();
        if(StringUtils.isNotEmpty(req.getUsername())){
            wrapper.like("username",req.getUsername());
        }
        if(StringUtils.isNotEmpty(req.getMobile())){
            wrapper.like("mobile",req.getMobile());
        }
        wrapper.orderByDesc("update_date");
        return Result.ok(baseMapper.selectPage(req.getPage(),wrapper));
    }

    @Override
    public Result findRoleIdsById(String id) {
        return Result.ok(baseMapper.findRoleIdsById(id));
    }

    @Override
    public Result saveUserRole(String userId, List<String> roleIds) {
        //1、在用户表新增
        baseMapper.deleteUserRoleByUserId(userId);
        //2、在中间表新增
        if(CollectionUtils.isNotEmpty(roleIds)){
            baseMapper.saveUserRole(userId,roleIds);
        }
        return Result.ok();
    }

    @Override
    public Result deleteUserRoleByUserId(String userId) {
        SysUser sysUser= baseMapper.selectById(userId);
        if(sysUser==null){
            return Result.error("用户不存在");
        }
        sysUser.setIsEnabled(0);
        sysUser.setUpdateDate(new Date());
        baseMapper.updateById(sysUser);
        return Result.ok();
    }
    @Autowired
    private PasswordEncoder passwordEncoder;

    @Override
    public Result checkPassword(SysUserCheckPasswordREQ req) {
        if(StringUtils.isEmpty(req.getId())){
            return Result.error("用户id不能为空");
        }
        if(StringUtils.isEmpty(req.getOldPassword())){
            return Result.error("密码不能为空");
        }
        //取出用户信息
        SysUser sysUser= baseMapper.selectById(req.getId());
        if(sysUser==null){
            return Result.error("用户不存在");
        }
        //
        boolean ok=passwordEncoder.matches(req.getOldPassword(),sysUser.getPassword());
        if(!ok){
            return Result.error("密码输入错误");
        }
        return Result.ok();
    }

    @Override
    public Result updatePassword(SysUserUpdatePasswordREQ req) {
        if(StringUtils.isEmpty(req.getId())){
            return Result.error("用户id不能为空");
        }
        if(StringUtils.isEmpty(req.getNewPassword())){
            return Result.error("新密码不能为空");
        }
        if(StringUtils.isEmpty(req.getRepPassword())){
            return Result.error("密码确认不能为空");
        }
        if(!req.getNewPassword().equals(req.getRepPassword())){
            return Result.error("两次密码不一致");
        }
        SysUser sysUser= baseMapper.selectById(req.getId());
        if(sysUser==null){
            return Result.error("用户不存在");
        }
        if(StringUtils.isNotEmpty(req.getOldPassword())){
            if(!passwordEncoder.matches(req.getOldPassword(),sysUser.getPassword())){
                return Result.error("新密码输入错误");
            }
        }
        sysUser.setPassword(passwordEncoder.encode(req.getNewPassword()));
        sysUser.setUpdateDate(new Date());
        baseMapper.updateById(sysUser);
        return Result.ok();
    }

    @Autowired
    private IFeignArticleController feignArticleController;

    @Autowired
    private IFeignQuestionController feignQuestionController;
    @Override
    public Result update(SysUser sysUser) {
        //1、查询用户信息
        SysUser user=baseMapper.selectById(sysUser);
        if(!StringUtils.equals(sysUser.getNickName(),user.getNickName())||!StringUtils.equals(sysUser.getImageUrl(),user.getImageUrl())){
            //2、只要有一个改变，则调用远程接口修改其他微服务中的用户信息
            //构建要远程传输的实体
            UserInfoREQ userInfoREQ=new UserInfoREQ(sysUser.getId(),sysUser.getNickName(),sysUser.getImageUrl());
            //远程修改article微服务中的用户信息
            feignArticleController.updateUserInfo(userInfoREQ);
            //远程修改question中的用户信息
            feignQuestionController.updateUserInfo(userInfoREQ);
        }
        //更新user表
        sysUser.setUpdateDate(new Date());
        baseMapper.updateById(sysUser);
        return Result.ok();
    }

    @Override
    public Result checkUsername(String username) {
        QueryWrapper<SysUser> wrapper=new QueryWrapper<>();
        wrapper.eq("username",username);
        SysUser sysUser= baseMapper.selectOne(wrapper);
        return Result.ok(sysUser==null ? false : true);
    }

    @Override
    public Result RegisterUser(RegisterREQ req) {
        if(StringUtils.isEmpty(req.getUsername())){
            return Result.error("用户名不能为空");
        }
        if(StringUtils.isEmpty(req.getPassword())){
            return Result.error("新密码不能为空");
        }
        if(StringUtils.isEmpty(req.getRePassword())){
            return Result.error("密码确认不能为空");
        }
        if(!req.getPassword().equals(req.getRePassword())){
            return Result.error("两次密码不一致");
        }
        Result result = checkUsername(req.getUsername());
        if((Boolean) result.getData()){
            return Result.error("用户名被注册过");
        }
        SysUser sysUser= new SysUser();
        sysUser.setUsername(req.getUsername());
        sysUser.setNickName(req.getUsername());
        sysUser.setPassword(passwordEncoder.encode(req.getPassword()));
        return Result.ok(baseMapper.insert(sysUser));
    }

    @Override
    public SysUser findUserByUsername(String username) {
        QueryWrapper<SysUser> wrapper=new QueryWrapper<>();
        wrapper.eq("username",username);
        return baseMapper.selectOne(wrapper);
    }
}
